package com.xiangyang.pos.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.xiangyang.pos.R;
import com.xiangyang.pos.bean.HttpBean;
import com.xiangyang.pos.bean.MobilePayDataBean;
import com.xiangyang.pos.bean.OrderErrorDataBean;
import com.xiangyang.pos.bean.PayDataBean;
import com.xiangyang.pos.bean.PayOrderBean;
import com.xiangyang.pos.constant.AppConstant;
import com.xiangyang.pos.http.HttpClient;
import com.xiangyang.pos.http.RequestParameters;
import com.xiangyang.pos.logger.Logger;
import com.xiangyang.pos.utils.SharedUtils;

import java.io.Serializable;
import java.util.List;

/**
 * Created by Administrator on 2017/8/21 0021.
 *
 * 确认收款（移动提交后台支付）
 *
 * @author YeDalin
 *
 */

public class ConfirmReceivablesActivity extends Activity {

    private TextView tvAllMoney;
    private ImageView ivConfirmReceivables;
    private ImageView ivGoBack;

    private int pay;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_receivables);
        initView();
        getMyIntent();
        setMyClick();
    }


    private void initView() {
        tvAllMoney = findViewById(R.id.tv_all_money);
        ivConfirmReceivables = findViewById(R.id.iv_confirm_receivables);
        ivGoBack = findViewById(R.id.iv_go_back);


        int money = SharedUtils.getIntPrefs(this, "all_money", -1);
        tvAllMoney.setText("￥" + money / 100.0);


    }

    //    获取总金额和支付方式（现金or移动端）
    private void getMyIntent() {

        Intent intent = getIntent();
        pay = intent.getIntExtra("pay", 0);
    }

    private void setMyClick() {
        ivConfirmReceivables.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (pay == 2) {
                    String pay_way = SharedUtils.getStringPrefs(ConfirmReceivablesActivity.this, "pmt_tag", "");
                    if(pay_way.equals("Weixin")){
                        cashPayHttp();
                    }else if(pay_way.equals("Alipay")){

                        mobilePayHttp();
                    }
//                    getHttp();
                } else if (pay == 1) {
                    cashPayHttp();

                } else {
                    Toast.makeText(ConfirmReceivablesActivity.this, "非法跳转", Toast.LENGTH_SHORT).show();
                }

            }
        });

        ivGoBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }


    //现金支付网络接口访问
    private RequestParameters getCashPayData() {

        String shopId = SharedUtils.getStringPrefs(this, "shopId", "");
        int all_money = SharedUtils.getIntPrefs(this, "all_money", -1) / 100;
        String phone = SharedUtils.getStringPrefs(this, "user_phone", "");
        String content = SharedUtils.getStringPrefs(this, "content", "");
        String employeeId = SharedUtils.getStringPrefs(this, "employeeId", "");
        String empname = SharedUtils.getStringPrefs(this, "name", "");

        String pay_way = SharedUtils.getStringPrefs(ConfirmReceivablesActivity.this, "pmt_tag", "");

        RequestParameters parameters = new RequestParameters();

        if(pay_way.equals("Weixin")){
            parameters.put("pay_way", pay_way);
        }else {
            parameters.put("pay_way", "Cash");
        }

        parameters.put("shopId", shopId);
        parameters.put("phone_num", phone);
        parameters.put("receivableMoney", all_money + "");
        parameters.put("orderArr", content);
        parameters.put("employeeId",employeeId);
        parameters.put("empname",empname);

        return parameters;
    }

//    private final String CASH_PAY_URL = AppConstant.POS_URL + "/Pay/An/cashpay";
    private void cashPayHttp() {

        String UserTOKEN = SharedUtils.getStringPrefs(this, "UserTOKEN", "");
        final String CASH_PAY_URL = AppConstant.POS_URL + "/Pay/An/cashpay"+"/u="+UserTOKEN;
        HttpClient httpClient = new HttpClient();
        httpClient.post(CASH_PAY_URL, getCashPayData(), new HttpClient.OnResponseListener() {
            @Override
            public void onResponse(String result) {
                Logger.e("xxx", "CashPay=" + result);
                if (!result.equals("Error")) {
                    Gson gson = new Gson();
                    OrderErrorDataBean bean = gson.fromJson(result, OrderErrorDataBean.class);
                    if (bean != null) {
                        if (bean.getStatus() == 1) {

                            SharedUtils.setStringPrefs(ConfirmReceivablesActivity.this,"out_trade_no",bean.getOrder().getOrdercode());

                            Intent intent = new Intent(ConfirmReceivablesActivity.this, DealDoneActivity.class);
                            startActivity(intent);
                        } else {
                            setNumberDialog(bean.getMsg(),2000);

                        }
                    }
                } else {
                    Toast.makeText(ConfirmReceivablesActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }



    //移动支付网络接口访问
    private RequestParameters getMobilePayData() {

        String pay_way = SharedUtils.getStringPrefs(this, "pmt_tag", "");
        String auth_code = SharedUtils.getStringPrefs(this, "auth_code", "");
        String shopId = SharedUtils.getStringPrefs(this, "shopId", "");
        int all_money = SharedUtils.getIntPrefs(this, "all_money", -1) / 100;
        String phone = SharedUtils.getStringPrefs(this, "user_phone", "");
        String content = SharedUtils.getStringPrefs(this, "content", "");
        String employeeId = SharedUtils.getStringPrefs(this, "employeeId", "");
        String empname = SharedUtils.getStringPrefs(this, "name", "");

        RequestParameters parameters = new RequestParameters();
        parameters.put("pay_way", pay_way);
        parameters.put("shopId", shopId);
        parameters.put("phone_num", phone);
        parameters.put("receivableMoney", all_money + "");
        parameters.put("orderArr", content);
        parameters.put("payCodeNumber", auth_code);
        parameters.put("employeeId",employeeId);
        parameters.put("empname",empname);

        return parameters;
    }

//    private final String MOBILE_PAY_URL = AppConstant.POS_URL + "/Pay/An/mobilePay";

    private void mobilePayHttp() {

        String UserTOKEN = SharedUtils.getStringPrefs(this, "UserTOKEN", "");
        final String MOBILE_PAY_URL = AppConstant.POS_URL + "/Pay/An/mobilePay"+"/u="+UserTOKEN;
        HttpClient httpClient = new HttpClient();
        httpClient.post(MOBILE_PAY_URL, getMobilePayData(), new HttpClient.OnResponseListener() {
            @Override
            public void onResponse(String result) {
                Logger.e("xxx", "mobilePay=" + result);
                if (!result.equals("Error")) {
                    Gson gson = new Gson();
                    MobilePayDataBean bean = gson.fromJson(result, MobilePayDataBean.class);
                    if (bean != null) {
                        if (bean.getStatus() == 10000) {
                            Toast.makeText(ConfirmReceivablesActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                            SharedUtils.setStringPrefs(ConfirmReceivablesActivity.this,"out_trade_no",bean.getOrder().getOut_trade_no());
                            Intent intent = new Intent(ConfirmReceivablesActivity.this, DealDoneActivity.class);
                            startActivity(intent);
                        }else if(bean.getStatus()==0){
                            setNumberDialog(bean.getMsg(),2001);
                        }else if(bean.getStatus()==10003){
                            Toast.makeText(ConfirmReceivablesActivity.this, "处理中，请等待", Toast.LENGTH_SHORT).show();
                            sureOrderPayHttp(bean);
                        }else {
                            Toast.makeText(ConfirmReceivablesActivity.this, "支付失败，请重新支付", Toast.LENGTH_SHORT).show();
                            Intent intent=new Intent(ConfirmReceivablesActivity.this,OrderListActivity.class);
                            startActivity(intent);
                        }
                    }


                } else {
                    Toast.makeText(ConfirmReceivablesActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }


    //确认订单支付状态网络请求
    private RequestParameters getOrderPayData(MobilePayDataBean bean){
        RequestParameters parameters=new RequestParameters();
        parameters.put("trade_no",bean.getOrder().getTrade_no());
        parameters.put("out_trade_no",bean.getOrder().getOut_trade_no());
        parameters.put("shopId",bean.getOrder().getShopid());
        parameters.put("mid",bean.getOrder().getMid());
        parameters.put("payment_total_free",bean.getOrder().getPayment_total_free());
        parameters.put("orderArr",bean.getOrder().getContent());
        return parameters;
    }


    private void sureOrderPayHttp(final MobilePayDataBean bean){

        String UserTOKEN = SharedUtils.getStringPrefs(this, "UserTOKEN", "");
        final String WAIT_URL=AppConstant.POS_URL+"/Pay/An/getAlipayOrderStatus"+"/u="+UserTOKEN;

        HttpClient httpClient=new HttpClient();
        httpClient.post(WAIT_URL, getOrderPayData(bean), new HttpClient.OnResponseListener() {
            @Override
            public void onResponse(String result) {
                Logger.e("xxx", "waitSurePay=" + result);
                if(!result.equals("Error")){
                    Gson gson=new Gson();
                    HttpBean httpBean=gson.fromJson(result,HttpBean.class);
                    if(httpBean!=null){
                        if(httpBean.getStatus()==10000){
                            Toast.makeText(ConfirmReceivablesActivity.this,"支付成功",Toast.LENGTH_SHORT).show();
                            SharedUtils.setStringPrefs(ConfirmReceivablesActivity.this,"out_trade_no",bean.getOrder().getOut_trade_no());
                            Intent intent = new Intent(ConfirmReceivablesActivity.this, DealDoneActivity.class);
                            startActivity(intent);
                        }else if(httpBean.getStatus()==10003){
                            Toast.makeText(ConfirmReceivablesActivity.this, "处理中，请等待", Toast.LENGTH_SHORT).show();
                            sureOrderPayHttp(bean);
                        }else{
                            Toast.makeText(ConfirmReceivablesActivity.this, "支付失败，请重新支付", Toast.LENGTH_SHORT).show();
                            Intent intent=new Intent(ConfirmReceivablesActivity.this,OrderListActivity.class);
                            startActivity(intent);
                        }
                    }
                }else {
                    Toast.makeText(ConfirmReceivablesActivity.this,"网络异常",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    //更改支付方式后暂时没用
    private void getHttp() {


        PayOrderBean bean = new PayOrderBean(this);

        HttpClient httpClient = new HttpClient();
        httpClient.post(AppConstant.PAY_ORDER_URL, bean.getPayData(), new HttpClient.OnResponseListener() {
            @Override
            public void onResponse(String result) {
                if (!result.equals("Error")) {
                    Gson gson = new Gson();
                    PayDataBean payDataBean = gson.fromJson(result, PayDataBean.class);
                    if (payDataBean != null) {
                        if (payDataBean.getErrcode() == 0) {
                            Toast.makeText(ConfirmReceivablesActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(ConfirmReceivablesActivity.this, DealDoneActivity.class);
                            startActivity(intent);
                        } else {
                            Toast.makeText(ConfirmReceivablesActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                            Logger.e("xxx", payDataBean.getErrcode() + "******" + payDataBean.getMsg());
                            Intent intent = new Intent(ConfirmReceivablesActivity.this, DealFailActivity.class);
                            startActivity(intent);
                        }
                    }
                } else {
                    Toast.makeText(ConfirmReceivablesActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //提示不能返回对话框（暂时没用）
    private void setMyDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setTitle("是否确认收款");
        builder.setMessage("确认收款后，将不能点击返回。");
        builder.setNegativeButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.setPositiveButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                builder.setCancelable(true);
            }
        });
        builder.show();
    }

    //订单商品数量超出提示
    private void setNumberDialog(final List<OrderErrorDataBean.OrderErrorData> msg, final int code) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        String str = "";
        for (int i = 0; i < msg.size(); i++) {

            str = str + (i + 1) + "." + msg.get(i).getName();
            if (i != msg.size() - 1) {
                str = str + "\n";
            }
        }

        /*Toast.makeText(this,"以下"+bean.getMsg().size()+"件商品已被APP用户抢购，请重新核对：\n"+str,Toast.LENGTH_LONG).show();

        Intent intent=new Intent(ConfirmReceivablesActivity.this,OrderDetailsActivity.class);
        intent.putExtra("list", (Serializable) bean.getMsg());
        setResult(1,intent);
        finish();*/

        builder.setTitle("警告");
        builder.setMessage("以下" + msg.size() + "种商品已被APP用户抢购，请重新核对商品数量：\n\n" + str);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(ConfirmReceivablesActivity.this, OrderDetailsActivity.class);
                intent.putExtra("list", (Serializable) msg);
                setResult(code, intent);
                finish();
            }
        });
        builder.show();

    }




}
